﻿using UnityEngine;
using System.Collections;
using System;

/// <summary>
/// 触碰控制器
/// </summary>
public class TouchProvider : IInputProvider
{
	/// <summary>
	/// 修正比例
	/// </summary>
	private float rate = 50f;

	/// <summary>
	/// 触点一
	/// </summary>
	private Touch oneTouch;
	
	/// <summary>
	/// 触点二
	/// </summary>
	private Touch twoTouch;
	
	/// <summary>
	/// 最后一次缩放距离
	/// </summary>
	private float lastScaleDistance;
	
	/// <summary>
	/// 当前缩放距离
	/// </summary>
	private float scaleDistance;
    public override Vector2 PointerPosition
    {
        get
        {
            return oneTouch.position;
        }
    }

    public TouchProvider(IInput input) : base(input)
    {
    }
    public override void Update()
	{
		// 如果只有一个触点
		if (Input.touchCount == 1) 
		{
			this.oneTouch = Input.touches[0];
			// 触点开始
			if(this.oneTouch.phase == TouchPhase.Began)
			{
                // 触发开始回调函数
                mInput.OnPointerDown(this.oneTouch.position);
            }
			// 触点移动
			else if(oneTouch.phase == TouchPhase.Moved)
			{
                // 触发移动回调函数
                mInput.OnPointerMove(this.oneTouch.position, this.oneTouch.deltaPosition);
			}
			// 触点结束
			else if(oneTouch.phase == TouchPhase.Ended)
			{
                // 触发结束回调函数
                mInput.OnPointerUp(this.oneTouch.position);
            }
		}
		// 如果有多个触点
		if(Input.touchCount > 1)
		{
			this.oneTouch = Input.touches[0];
			this.twoTouch = Input.touches[1];
			// 如果是缩放
			if(oneTouch.phase == TouchPhase.Moved || twoTouch.phase == TouchPhase.Moved)
			{
				this.scaleDistance = Vector2.Distance(this.oneTouch.position, this.twoTouch.position);
                // 触发缩放回调函数
                if(this.lastScaleDistance != 0)
                    mInput.OnPointerZoom((this.oneTouch.position + this.twoTouch.position) /2, (this.lastScaleDistance - this.scaleDistance)/2);
				this.lastScaleDistance = this.scaleDistance;
            }
            if (oneTouch.phase == TouchPhase.Ended || twoTouch.phase == TouchPhase.Ended)
            {
                this.lastScaleDistance = 0;
            }
            if (oneTouch.phase == TouchPhase.Canceled || twoTouch.phase == TouchPhase.Canceled)
            {
                this.lastScaleDistance = 0;
            }
        }
    }
}
